//
//  ViewController.m
//  图片轮播
//
//  Created by song on 15/1/9.
//  Copyright (c) 2015年 song. All rights reserved.
//

#define JOCount 5
#import "ViewController.h"

@interface ViewController ()  <UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;

@property (weak, nonatomic) IBOutlet UIPageControl *pagecontrol;

@property (nonatomic ,strong) NSTimer *timer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    CGFloat imageW = self.scrollview.frame.size.width;
    CGFloat imageH = self.scrollview.frame.size.height;
    for(int i=0 ;i<5 ;i++)
    {
        UIImageView *imageview = [[UIImageView alloc]init];
        
        CGFloat imageX = i* imageW;
        CGFloat imageY =0;
        
        imageview.frame =CGRectMake(imageX, imageY, imageW, imageH);
        
        NSString *name = [NSString stringWithFormat:@"img_0%d",i+1];
        imageview.image = [UIImage imageNamed:name];
        
        [self.scrollview addSubview:imageview];
    }
    
    self.scrollview.delegate = self;
    CGFloat contentW = 5 * imageW;
    self.scrollview.contentSize =CGSizeMake(contentW, 0);
    self.scrollview.showsHorizontalScrollIndicator =NO;
    self.scrollview.pagingEnabled = YES; //设置分页，必须保证图片的宽度，需要和 scrowllview 的宽度是一样的
    self.pagecontrol.numberOfPages = 5;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    
}

-(void) nextImage
{
    
    if(self.pagecontrol.currentPage ==(JOCount-1))
    {
        self.pagecontrol.currentPage =0 ;
    }else{
        self.pagecontrol.currentPage++;
    }
    CGFloat offsetX =self.pagecontrol.currentPage * self.scrollview.frame.size.width;
    CGPoint offset = CGPointMake(offsetX, 0);
    [self.scrollview setContentOffset:offset animated:YES ];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = scrollView.contentOffset.x / self.scrollview.frame.size.width ;
    NSLog(@"%d", page);
    self.pagecontrol.currentPage = page;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 停止定时器（ 一旦定时器停止了，就不能再使用了）
    [self.timer invalidate];
    self.timer =nil;
}
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
        self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
}

@end
